import web, datetime
import json, time
import subprocess 

import os
import re
import logging
import logging.handlers

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)

class Process:
    @staticmethod
    def get_all():
        args = ("systemctl --no-pager --no-legend").split()        
        processes = []
        try:
            ret = subprocess.check_output(args)        
            for line in ret.split("\n"):    
                m = re.search('^(.+\.\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+(.*)', line)   
                if m:
                    processes.append({
                        "unit": m.group(1), 
                        "load": m.group(2), 
                        "active": m.group(3), 
                        "sub": m.group(4), 
                        "desc": m.group(5)
                    })
        except OSError as e:
            logging.error("Error getting processes: "+str(e))
        except subprocess.CalledProcessError as e:
            logging.error("Error getting processes: "+str(e))        
        return processes

    def get_status(self):
        unit = self.name
        args = ("systemctl status "+unit).split()
        
        status = "unknown"
        try:
            p = subprocess.Popen(args, stdout=subprocess.PIPE)
            status = p.communicate()[0]            
        except OSError as e:
            logging.warning(e)
        return status

    def __init__(self, name):
        self.name = name

    def restart(self):
        """ Restart this process """
        try:
            return (subprocess.call(["systemctl",  "restart", self.name]) == 0)
        except OSError: 
            return False

    

